/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**BroadcastReceiver that handles:
 * - Plugins getting (uninstalled by user)
 * - Device boot
 * - Plugin wants to be checked
 * */
public class Reciever extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

		if(intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED ))
		{
			//remove plugin from DB when needed
			if(intent.getExtras().getBoolean(Intent.EXTRA_REPLACING)==false)
			{
				Database db = new Database(context);
				db.open();
				if(db.removePlugin(intent.getData().getSchemeSpecificPart()))
				{
    	    		ConditionCecker.notify(context, 0, false,
    	    				context.getString(R.string.reciever_removed), context.getString(R.string.app_name), context.getString(R.string.reciever_removed),
    						null);
				}
				db.close();
			}
			return;
		}
		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
		{
			//start periodic timer
			TimedProfiles.aktTimer(context);

			//start timer if needed
	        Database db = new Database(context);
	        db.open();
	        long d = db.getNextDeadLine();
	        db.close();
	        if(d!=0)
	        {
	        	TimedProfiles.aktTimerOnce(context, d);
	        }
			return;
		}

		if(intent.getAction().equals(TimedProfiles.ACTION_REQUEST))
		{
			//a plugin wants to be queryed
			String editClass = intent.getExtras().getString(TimedProfiles.INTENT_PACKAGE);
    		
    		Intent open = new Intent(context, ConditionCecker.class);
    		open.setAction(ConditionCecker.ACTION_CHECK_PLUGIN);
    		open.putExtra(TimedProfiles.INTENT_PACKAGE, editClass);
    		context.startService(open);
    		
			return;
		}
		if(intent.getAction().equals("com.twofortyfouram.locale.intent.action.START_LOCALE"))
		{
			//start TP - used from market
	        context.startActivity(new Intent(context, TimedProfiles.class));
			return;
		}		
	}
}

